
var app=getApp();
Page({
  data: {
    iswm: false,
    carts: [],               // 购物车列表
    hasList: false,          // 列表是否有数据
    totalPrice: "",           // 总价，初始为0
    total_num:"",             //产品数量
    selectAllStatus: true,    // 全选状态，默认全选
    items: [
      { name: 'CHN', value: '线上支付', checked: 'true'},
      { name: 'USA', value: '线下支付' },
      
    ],
    
  },
  radioChange: function (e) {
    var value = e.detail.value;
    this.setData({
      radio: e.detail.value
    })
    // if (value == 'USA') {
    //   this.setData({
    //     iswm: false
    //   })
    // }
    // else {
    //   this.setData({
    //     iswm: true
    //   })
    // }
  },
  onShow() {
   var that=this;
   wx.request({
     url: app.appUrl + '/address/defaultadds',
     data: {
       uid: wx.getStorageSync('userinfo').uid
     },
     method: "post",
     success: function (res) {
      if(res.data.code==1){

        that.setData({
          adds: res.data.data
        })
      }else{
        wx.showToast({
          title: '您还没有设置默认地址',
          icon:'none',
          duration:1000,
          success:function(){
          setTimeout(function(){
            wx.navigateTo({
              url: '/pages/ads/ads',
            })
          },1000)
          }
        })
      }
     }
   })
    // console.log(this.carts.length)
  },
  
  study: function () {
    wx.navigateTo({
      url: '../study/study'
    })
  },
  ads: function () {
    wx.navigateTo({
      url: '../ads/ads'
    })
  },
  getTotalPrice() {
    let carts = this.data.carts;                  // 获取购物车列表
    let total = 0;
    let total_num = 0;
    for (let i = 0; i < carts.length; i++) {         // 循环列表得到每个数据
      if (carts[i].selected) {                   // 判断选中才会计算价格
        total_num += parseInt(carts[i].num);
        total += carts[i].num * carts[i].price;     // 所有价格加起来
      }
      
    }
    // console.log(total_num)
    this.setData({                                // 最后赋值到data中渲染到页面
      carts: carts,
      total_num: total_num,
      totalPrice: total.toFixed(2)
    });
  },
  selectList(e) {
    const index = e.currentTarget.dataset.index;    // 获取data- 传进来的index
    let carts = this.data.carts;                    // 获取购物车列表
    const selected = carts[index].selected;         // 获取当前商品的选中状态
    carts[index].selected = !selected;              // 改变状态
    this.setData({
      carts: carts
    });
    this.getTotalPrice();                           // 重新获取总价
  },
  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;    // 是否全选状态
    selectAllStatus = !selectAllStatus;
    let carts = this.data.carts;

    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus;            // 改变所有商品状态
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      carts: carts
    });
    this.getTotalPrice();                               // 重新获取总价
  },
  // 增加数量
  addCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let num = carts[index].num;
    num = num + 1;
    carts[index].num = num;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },
  // 减少数量
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let num = carts[index].num;
    if (num <= 1) {
      return false;
    }
    num = num - 1;
    carts[index].num = num;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },
  deleteList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    carts.splice(index, 1);              // 删除购物车列表里这个商品
    this.setData({
      carts: carts
    });
    if (!carts.length) {                  // 如果购物车为空
      this.setData({
        hasList: false              // 修改标识为false，显示购物车为空页面
      });
    } else {                              // 如果不为空
      this.getTotalPrice();           // 重新计算总价格
    }
  },
  onLoad: function (res) {
    var that=this;
    wx.request({
      url: app.appUrl +'/goods/detail',
      data:{
        goodsid:res.id
      },
      success:function(ress){
        console.log(ress)
        that.setData({
          hasList: true,        // 既然有数据了，那设为true吧
          carts: [
            { id: 1, title: ress.data.data.name, image: ress.data.data.pic, num: parseInt(res.num), price: ress.data.data.min_price, selected: true }
          ],
          totalPrice: ress.data.data.min_price * parseInt(res.num),
          total_num: parseInt(res.num),
          iswm: true,
          goodsid:ress.data.data.goodsid
        });
      }
    })
 
 
  },
  toSelectYhq:function(){
    wx.navigateTo({
      url: '../selectyhq/selectyhq',
    })
  },

  //留言
  bindinput:function(e){
    var txt = e.detail.value
    this.setData({
      text: txt
    })
    console.log(txt)
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },
  /**
   * 订单支付
   */
  pay:function(){
    var that=this;

    wx.showLoading({
      title: '请稍后',
      success:function(){
        wx.request({
          url: app.appUrl +'/order/insertOrder',
          data:{
            uid:wx.getStorageSync('userinfo').uid,
            goods_data:{
              remark: that.data.text ? that.data.text:'',
              goodsid:that.data.goodsid,
              number: that.data.total_num
            },
            
          },
          method:'post',
          success:function(rs){
        
            if (!that.data.radio || that.data.radio == 'CHN') {
              that.goodspay(rs);
            } else {
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                content: '确定通过线下人员交易',
                success: function (res) {
                  if (res.confirm == 1) {
                    wx.request({
                      url: app.appUrl + '/order/trade',
                      data: {
                        uid: wx.getStorageSync('userinfo').uid,
                        order_no: rs.data.data.order_no,
                      },
                      method: 'post',
                      success: function (e) {
                       
                        if (e.data.code == 1) {
                        
                          wx.showToast({
                            title: e.data.msg,
                            success:function(){
                              wx.navigateTo({
                                url: '/pages/myorder/myorder',
                              })
                            }
                          })
                        } else {
                    
                          wx.showToast({
                            title: e.data.msg,
                            icon: 'none'
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
         
          }
        })
      }
    })
    
  }
  ,
  goodspay:function(rs){
  
   
      wx.request({
        url: app.appUrl + '/order/orderPayParams',
        data: {
          order_no: rs.data.data.order_no,
          uid: wx.getStorageSync('userinfo').uid,
          title: '商品支付'
        },
        method: 'post',
        success: function (e) {
          if (e.data.code == 1) {
            wx.requestPayment({
              timeStamp: e.data.data.weixin.timeStamp,
              nonceStr: e.data.data.weixin.nonceStr,
              package: e.data.data.weixin.package,
              signType: e.data.data.weixin.signType,
              paySign: e.data.data.weixin.paySign,
              success: function () {
                wx.navigateTo({
                  url: '/pages/myorder/myorder',
                })
                wx.hideLoading();
              },
              fail: function () {
                wx.hideLoading();
                wx.showToast({
                  title: '支付失败',
                  icon: 'none'
                })
              }
            })
          } else {
            wx.hideLoading();
            wx.showToast({
              title: '失败',
              icon: 'none'
            })
          }
        }
      })

   
  }
})